import random
import re
from datetime import datetime
from urllib import response

from flask import abort, jsonify
from flask import current_app
from flask import make_response
from flask import request
from flask import session

from info import redis_store, db
from info.models import User, News
from info.modules.passport import passport_url
from info.response_code import RET
from info.utils.captcha.captcha import captcha
from info import constants
from info.lib.yuntongxun.sms import CCP


@passport_url.route('/news_list')
def newlist():
    """
    获取新闻首页数据
    :return:
    """
    cid = request.args.get('cid',"1")
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')
    # 2. 校验参数
    try:
        cid=int(cid)
        page=int(page)
        per_page=int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数有误')

    filters=[News.status==0]
    if cid != 1: # 查询的不是最新的数据
        filters.append( News.category_id== cid)

    try:
        paginates=News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')

    # 取到当前页的数据
    news_model_list = paginates.items
    total_page =paginates.pages
    current_page = paginates.page

    # 遍历news_model_list对象，吧对象里数据放到列表中
    news_list = []
    for news in news_model_list:
        news_list.append(news.to_basic_dict())

    data_querying=True

    data={
        'total_page':total_page,
        'current_page':current_page,
        'news_list':news_list,
        "data_querying":data_querying

    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)




@passport_url.route('/login', methods=['POST'])
def login():
    # current_app.logger.info('登陆入口')
    """
    　后端
    接受用户输入的手机号，密码
    校验参数完整性，校验手机号是否符合要求
    查数据库，看手机号是否存在
    (手机号存在)校验密码是否一致
    保存登陆信息(session,last_login)
    返回结果
    :return:
    """
    request_dict = request.json
    mobile = request_dict.get('mobile')
    password = request_dict.get('password')
    print('denglu', mobile, password)
    if not all([mobile, password]):
        return jsonify(errno=RET.NODATA, errmsg='请输入数据')

    result = re.match('1[3-57-9]\\d{9}', mobile)
    print(result)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg='手机号参数错误')
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='手机号查询错误')

    if not user:
        return jsonify(errno=RET.NODATA, errmsg='用户不存在')

    if not user.check_passward(password):
        return jsonify(errno=RET.NODATA, errmsg='手机号或者密码错误')

    session['mobile'] = user.mobile
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name


    User.last_login = datetime.now()

    return jsonify(errno=RET.OK, errmsg='注册成功')


@passport_url.route("/logout")
def logout():
    session.pop('user_id')
    session.pop('nick_name')
    session.pop('mobile')
    session.pop('is_admin',None)

    return jsonify(errno=RET.OK, errmsg='退出成功')


@passport_url.route('/register', methods=["POST"])
def register():
    """注册账号
    # 后端
    获取用户输入的手机号，短息验证码，密码；
    校验参数完整性
    校验手机号（是否被注册过）
    从redis中取出短信验证码，跟用户输入的短信验证码校验
    创建用户，将用户的手机号，密码，昵称，登陆时间存入数据库
    session中保存相关信息
    返回结果
    """
    # 获取手机号，手机验证码，密码
    request_dict = request.json
    mobile = request_dict.get('mobile')
    mobile_sms_code = request_dict.get('smscode')
    password = request_dict.get('password')
    # print("打印登陆", mobile, mobile_sms_code, password)

    # 检验手机号，手机验证码，密码是否为空
    if not all([mobile, mobile_sms_code, password]):
        return jsonify(errno=RET.NODATA, errmsg='请输入数据')
    # 验证手机号是否正确
    result = re.match('1[3-57-9]\\d{9}', mobile)
    # print(result)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg='手机号参数错误')
    # 检验手机号是否已经被注册过
    # if db.query.filter(User.mobile==mobile).first:
    #     return jsonify(errno=RET.DATAERR,errmsg='手机号已经被注册过')
    # 取出存在redis里面的验证码和提交上来的验证码是否一致
    try:
        redis_sms_code = redis_store.get('sms' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    if not redis_sms_code:
        # print(redis_sms_code)
        return jsonify(errno=RET.DATAERR, errmsg='验证码已过期')

    if redis_sms_code != mobile_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入错误')
    # 创建一个新用户
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.last_login = datetime.now()
    user.password = password
    # try:
    #     db.session.add(user)
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    #     db.session.rollback()
    #     return jsonify(errno=RET.DBERR, errmsg='数据保存失败')
    # 保存当前用户的登陆状态
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile

    return jsonify(errno=RET.OK, errmsg='注册成功')


@passport_url.route('/image_code')
def image_code():
    # print('哈哈哈哈哈')
    """创建验证码获取视图"""
    # 步骤：
    # 1.获取参数

    # 2.生成验证码
    # 3.删除之前验证码并保存当前验证码
    # 4.错误处理
    # 5.响应返回
    image_code_id = request.args.get("code_id", None)
    if not image_code_id:
        return abort(403)
    name, text, image = captcha.generate_captcha()
    current_app.logger.info(text)
    try:
        redis_store.set('code_id' + image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    response = make_response(image)
    response.headers["Contens-Type"] = "image/jpg"
    return response


@passport_url.route('/sms_code', methods=["POST"])
def get_sms_code():
    # print('哈哈哈哈啊哈哈哈哈')
    '''获取手机验证码'''
    # 1.
    # 接收参数并判断是否有值
    # 2.
    # 校验手机号是正确
    # 3.
    # 通过传入的图片编号去redis中查询真实的图片验证码内容
    # 4.
    # 进行验证码内容的比对
    # 5.
    # 生成发送短信的内容并发送短信
    # 6.
    # redis中保存短信验证码内容(注册的时候需要用到)
    # 7.
    # 返回响应

    #   """
    #   '{"mobiel": "18811111111", "image_code": "AAAA", "image_code_id": "u23jksdhjfkjh2jh4jhdsj"}'
    # request.args.get()
    request_dict = request.json
    # print(request_dict)
    mobiel = request_dict.get('mobile')
    image_code = request_dict.get('image_code')
    image_code_id = request_dict.get('image_code_id')
    # print('打印', mobiel, image_code_id, image_code)
    # print('哈哈哈哈啊哈哈哈哈')
    if not all([mobiel, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    result = re.match('1[3-57-9]\\d{9}', mobiel)
    # print(result)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg='手机号参数错误')
    try:
        real_image_code = redis_store.get('code_id' + image_code_id)
        # print(real_image_code)
    except Exception as e:
        current_app.logger.error(e)
        # print(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg='验证码已过期')

    if real_image_code.upper() != image_code.upper():
        result1 = image_code.upper()
        # print(result1)
        return jsonify(errno=RET.DBERR, errmsg='验证码输入错误')
    # 验证手机号是否已经注册
    # try:
    #     user = db.query.filter(mobiel).first
    # except Exception as e:
    #     current_app.logging.error(e)
    #     print(e)
    #     return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    # if user:
    #     return jsonify(errno=RET.DATAEXIST, errmsg='手机号已注册')
    # # 5. 如果一致，生成短信验证码的内容(随机数据)
    # 随机数字 ，保证数字长度为6位，不够在前面补上0
    sms_code_str = '%06d' % random.randint(0, 999999)
    # print(sms_code_str)
    current_app.logger.debug("短信验证码是%s" % sms_code_str)
    # result = CCP().send_template_sms(mobiel, [sms_code_str, 5], 1)
    # print(result)
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")

    try:
        redis_store.set('sms' + mobiel, sms_code_str, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        # print(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errsmg='发送成功')
